package com.heima.search.service.impl;

import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.heima.common.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDto;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.model.search.pojo.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author TheCai
 * @date 2021/6/9 19:49
 */
@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

  @Autowired BehaviorFeign behaviorFeign;

  @Autowired MongoTemplate mongoTemplate;
  /**
   * 保存用户搜索历史记录
   *
   * @param dto
   */
  @Override
  @Async("taskExecutor") // 开启异步处理
  public void insert(UserSearchDto dto) {
    // 异步记录 用户搜索历史记录
    if (dto == null) {
      throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
    }
    // 1.远程查询行为实体数据
    ApBehaviorEntry behaviorEntry =
        behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), dto.getEquipmentId());
    if (behaviorEntry == null) {
      log.error(
          "记录搜索历史记录失败,未查询到对应的行为实体数据 用户id : {} ,设备id: {}", dto.getEntryId(), dto.getEquipmentId());
      return;
    }
    // 2.根据行为实体id查询  是否记录过该历史记录
    Query query =
        Query.query(
            Criteria.where("entryId")
                .is(behaviorEntry.getId())
                .and("keyword")
                .is(dto.getSearchWords()));
    ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
    if (apUserSearch != null) {
      // 3.如果有历史记录,修改时间为最新
      apUserSearch.setCreatedTime(new Date());
    } else {
      // 4.如果没有就插入
      apUserSearch = new ApUserSearch();
      apUserSearch.setEntryId(behaviorEntry.getId());
      apUserSearch.setKeyword(dto.getSearchWords());
      apUserSearch.setCreatedTime(new Date());
      mongoTemplate.insert(apUserSearch);
    }
  }

  /**
   * 查询用户搜索历史记录 显示10条
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult findUserSearch(UserSearchDto dto) {

    // 1.检查参数

    ApUser user = AppThreadLocalUtils.getUser();

    ApBehaviorEntry behaviorEntry =
        behaviorFeign.findByUserIdOrEquipmentId(
            user == null ? null : user.getId(), dto.getEquipmentId());
    if (behaviorEntry == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到关联的行为实体数据");
    }

    // 按照时间倒序  默认显示十条
    Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
            .with(Sort.by(Sort.Direction.DESC,"createdTime")).limit(10);
    List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
    // 3.
    return ResponseResult.okResult(apUserSearchList);
  }

  @Override
  public ResponseResult delUserSearch(HistorySearchDto dto) {

//    if (dto.getId()==null){
//      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//
//    }
    ApUser user = AppThreadLocalUtils.getUser();
    ApBehaviorEntry behaviorEntry =
            behaviorFeign.findByUserIdOrEquipmentId(
                    user == null ? null : user.getId(), dto.getEquipmentId());
    if (behaviorEntry == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到关联的行为实体数据");
    }
    //根据行为实体id及搜索历史记录 删除历史记录
    Query query = Query.query(Criteria.where("entryId")
            .is(behaviorEntry.getId()).and("id").is(dto.getId()));
    mongoTemplate.remove(query, ApUserSearch.class);

    return ResponseResult.okResult();
  }
}
